package com.loe.ui.view

import android.content.Context
import android.view.View
import android.widget.FrameLayout
import androidx.annotation.Keep
import com.loe.ui.*
import com.loe.ui.api.IUiViewGroup
import com.loe.ui.api.ViewGroupApi
import com.loe.ui.page.UiPage
import com.quickjs.JSObject

@Keep
open class UiFrameLayout : FrameLayout, IUiViewGroup
{
    constructor(context: Context) : super(context)

    override var uiPage: UiPage? = null

    override val jsObject by lazy { ViewGroupApi(this).jsObject }

    override fun setUI(ui: JSObject, uiPage: UiPage?): View
    {
        this.uiPage = uiPage

        // click
        ui.gotHasBoolean("isClick") { setClick(it) }

        // 递归子元素
        ui.gotHasArray("childs")
        { childs ->
            childs.forEach<JSObject>
            {
                uiPage?.createUI(it, this)
            }
        }
        return this
    }

    override var onSelect: (() -> Unit)? = null

    /********************************************** 点击 ****************************************/

    fun setClick(isClick: Boolean)
    {
        isAlpha = isClick
        isClickable = isClick
    }

    private var isAlpha = false

    override fun dispatchSetPressed(pressed: Boolean)
    {
        if (isAlpha) alpha = if (pressed || !isEnabled) 0.75f else 1f
        super.dispatchSetPressed(pressed)
    }

    override fun setEnabled(enabled: Boolean)
    {
        if (isAlpha) alpha = if (enabled) 1f else 0.75f
        super.setEnabled(enabled)
    }
}